package com.link.base.tencent.corpwx.access.controller;

import com.alibaba.fastjson.JSONObject;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.cllog.LCLogger;
import com.link.base.tencent.corpwx.access.service.CorpWxAccessService;
import com.link.base.tencent.corpwx.agent.service.AgentService;
import com.link.base.wechat.basic.util.MsgUtil;
import com.link.base.wechat.basic.util.Sha1Util;
import com.link.core.util.StringUtils;
import org.dom4j.Element;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 企业微信消息、事件接入
 *
 * @author 欧阳振强
 * @date 2019/1/2
 */
@Controller
@RequestMapping("/link/corpwx/access")
public class CorpWxAccessController {
    /**
     * 企业微信相关参数
     */
    private static String corpId = "wwe71019f3bd03b677";
    private static String token = "Ook1FwLPkGOiooEmiaPnp1YXd75YZ4m";
    private static String aesKey = "5U8jo0XotEehfHkyuvD636XJUKACmxoaUvWy2WxCmFc";

    @Resource
    private CorpWxAccessService corpWxAccessService;
    @Resource
    private AgentService agentService;

    /**
     * 消息、事件入口
     *
     * @author 欧阳振强
     * @date 2019/1/2
     */
    @RequestMapping(value = "/auth", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void auth(HttpSession session,
                     HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 转码UTF-8，防止乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        // 返回结果
        String result = "";
        try {
            JSONObject jsonObject = corpWxAccessService.parseEventXml(request, corpId, token, aesKey);
            if (StringUtils.isNotBlank(jsonObject.getString("verifyFlag"))) {
                result = jsonObject.getString("verifyFlag");
            } else {
                String resultStr = jsonObject.getString("busFlag");
                // 解析xml
                Element root = MsgUtil.resolveXml(resultStr);
                // 企业微信CorpID
                String corpId = root.elementText("ToUserName");
                // 成员UserID
                String userId = root.elementText("FromUserName");
                // 应用Id
                String agentId = root.elementText("AgentID");
                // 消息类型
                String msgType = root.elementText("MsgType");
                LCLogger.info().withMessageKey("auth").withMessage(
                        "企业微信CorpID－>" + corpId + "，成员UserID->" + userId + "，应用Id->" + agentId + "，消息类型－>" + msgType).flush();
                if (MsgUtil.MESSAGE_TYPE_TEXT.equals(msgType)) {
                    LCLogger.info().withMessageKey("auth").withMessage("文本消息111.").flush();
                    LCLogger.info().withMessageKey("auth").withMessage("文本消息.").flush();
                } else if (MsgUtil.MESSAGE_TYPE_IMAGE.equals(msgType)) {
                    LCLogger.info().withMessageKey("auth").withMessage("图片消息.").flush();
                } else if (MsgUtil.MESSAGE_TYPE_VOICE.equals(msgType)) {
                    LCLogger.info().withMessageKey("auth").withMessage("语音消息.").flush();
                } else if (MsgUtil.MESSAGE_TYPE_VEIDO.equals(msgType)) {
                    LCLogger.info().withMessageKey("auth").withMessage("视频消息.").flush();
                } else if (MsgUtil.MESSAGE_TYPE_LOCATION.equals(msgType)) {
                    LCLogger.info().withMessageKey("auth").withMessage("地理位置消息.").flush();
                } else if (MsgUtil.MESSAGE_TYPE_LINK.equals(msgType)) {
                    LCLogger.info().withMessageKey("auth").withMessage("链接消息.").flush();
                } else if (MsgUtil.EVENT_TYPE.equals(msgType)) {
                    LCLogger.info().withMessageKey("auth").withMessage("事件消息").flush();
                    // 事件类型
                    String event = root.elementText("Event");
                    if (MsgUtil.EVENT_TYPE_SUBSCRIBE.equals(event)) {
                        LCLogger.info().withMessageKey("auth").withMessage("成员关注事件.").flush();
                    } else if (MsgUtil.EVENT_TYPE_UNSUBSCRIBE.equals(event)) {
                        LCLogger.info().withMessageKey("auth").withMessage("取消关注事件.").flush();
                    } else if (MsgUtil.EVENT_TYPE_ENTER_AGENT.equals(event)) {
                        LCLogger.info().withMessageKey("auth").withMessage("进入应用事件.").flush();
                    } else if (MsgUtil.EVENT_TYPE_LOCATION.equals(event)) {
                        LCLogger.info().withMessageKey("auth").withMessage("上报地理位置事件.").flush();
                    } else if (MsgUtil.EVENT_TYPE_BATCH_JOB_RESULT.equals(event)) {
                        LCLogger.info().withMessageKey("auth").withMessage("异步任务完成事件.").flush();
                    } else if (MsgUtil.EVENT_TYPE_CLICK.equals(event)) {
                        LCLogger.info().withMessageKey("auth").withMessage("菜单事件.").flush();
                    } else if (MsgUtil.EVENT_TYPE_VIEW.equals(event)) {
                        LCLogger.info().withMessageKey("auth").withMessage("点击菜单链接跳转事件.").flush();
                    } else if (MsgUtil.EVENT_TYPE_SCAN_CODE_PUSH.equals(event)) {
                        LCLogger.info().withMessageKey("auth").withMessage("扫码推事件.").flush();
                    } else if (MsgUtil.EVENT_TYPE_SCAN_CODE_WAIT_MSG.equals(event)) {
                        LCLogger.info().withMessageKey("auth").withMessage("扫码推事件且弹出“消息接收中”提示框事件.").flush();
                    } else if (MsgUtil.EVENT_TYPE_PIC_SYSPHOTO.equals(event)) {
                        LCLogger.info().withMessageKey("auth").withMessage("弹出系统拍照发图事件.").flush();
                    } else if (MsgUtil.EVENT_TYPE_PIC_PHOTO_OR_ALBUM.equals(event)) {
                        LCLogger.info().withMessageKey("auth").withMessage("弹出拍照或者相册发图事件.").flush();
                    } else if (MsgUtil.EVENT_TYPE_PIC_WEIXIN.equals(event)) {
                        LCLogger.info().withMessageKey("auth").withMessage("弹出微信相册发图器事件.").flush();
                    } else if (MsgUtil.EVENT_TYPE_LOCATION_SELECT.equals(event)) {
                        LCLogger.info().withMessageKey("auth").withMessage("弹出地理位置选择器事件.").flush();
                    } else {
                        LCLogger.info().withMessageKey("auth").withMessage("打印事件类型======." + event).flush();
                    }
                }
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        response.getWriter().write(result);
    }

    /**
     * 获取微信js-sdk签名
     * @author 欧阳振强
     * @date 2019/1/2
     */
    @RequestMapping(value = "/getSignature", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getSignature(HttpSession session,
                                            HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("getSignature").withMessage("开始生成微信签名.").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            // 应用Id
            String agentId = request.getParameter("agentId");
            if (StringUtils.isBlank(agentId)) {
                throw new BasicServiceException("agentId不能为空！");
            }
            String agentFlag = request.getParameter("agentFlag");
            String ticket = agentService.getExistJsTicket(agentId);
            String agentSignature = "";
            String url = request.getParameter("jsUrl");
            String noncestr = UUID.randomUUID().toString();
            String timestamp = Long.toString((System.currentTimeMillis()) / 1000);
            String signatureString = "jsapi_ticket="
                    + ticket
                    + "&noncestr=" + noncestr
                    + "&timestamp=" + timestamp
                    + "&url=" + url;
            String signature = Sha1Util.getJsSHA1(signatureString);
            if (StringUtils.isNotBlank(agentFlag)) {
                String agentTicket = agentService.getExistAgentJsTicket(agentId);
                String subString = signatureString.substring(signatureString.indexOf("=") + 1, signatureString.indexOf("&"));
                signatureString = signatureString.replace(subString, agentTicket);
                agentSignature = Sha1Util.getJsSHA1(signatureString);
            }
            String error = "error";
            if (error.equals(signature)) {
                throw new BasicServiceException("签名失败！");
            }
            result.put("signature", signature);
            result.put("noncestr", noncestr);
            result.put("timestamp", timestamp);
            result.put("agentSignature",agentSignature);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

}
